<?php

namespace app\api\controller;
use app\admin\model\Agent;
use app\admin\model\Archives;
use app\common\controller\Api;
use think\Db;

/**
 * 客户更新UID
 */
class ArchivesUid extends Api
{
    protected $noNeedLogin = ['*'];
    public $num = 0;
    public $page = 0;
    public $a_agent = [];//所有总经理级别的客户
    public $ids = [];//所有修改的id
    /**
     * /api/archives_uid/index
     * php public/index.php api/archives_uid/index
     */
    public function index()
    {
        $this->initData();
        $this->updataUid();
    }

    public function updataUid()
    {
        //Db::startTrans();
        foreach ($this->a_agent as $k => $v){
            if($v['u_id'] > 0){
                $teamList = Agent::getDownTeamUser($v['mobile'], 1);
                if($teamList){
                    $mobiles = array_column($teamList,"mobile");
                    array_walk($mobiles, function(&$vv){ $vv = intval($vv); });
                    $arcList = Archives::where(['mobile'=>['in',$mobiles],'u_id'=>0])->select();
                    if($arcList){
                        Archives::where(['mobile'=>['in',$mobiles],'u_id'=>0])->update(['u_id'=>$v['u_id'],'updatetime'=>time()]);
                        $this->page ++;
                        $this->num += count($arcList);
                        $this->ids = array_merge($this->ids?:[], array_column($arcList,'id')?:[]);
                        echo $this->page . DS . $v['mobile'] . DS . count($arcList) . PHP_EOL;
                    }
                }
            }
        }
        //Db::rollback();
        //Db::commit();
        echo "End     $this->num";
        file_put_contents(self::getLogPath(),print_r($this->ids,true));
        die;
    }

    public function initData()
    {
        $list = Agent::where(['type' => 1, 'is_delect' => 0])
            ->field('id,username,mobile,company_name,manager,u_id')
            ->select();
        $list = collection($list)->toArray();
        $this->a_agent = $list;
    }

    public static function getLogPath()
    {
        $addonTmpDir = RUNTIME_PATH . DS . 'archives_uid' . DS ;
        if (!is_dir($addonTmpDir)) {
            @mkdir($addonTmpDir, 0755, true);
        }
        return $addonTmpDir . date('Y_m_d') ."archives_uid" . ".log";//最终结果
    }
}